import pika
import json

from push import push_client
from database import mongodb

class ResultTracing:
    def __init__(self, queue_name="trade_result"):
        self.queue_name = queue_name
        self.connection = None
        self.channel = None

        self.push_api = push_client.PushClient()
        self.db_client = mongodb.MongoConnector()

    def push_message(self, recv_data):
        if recv_data["operation"] == "buy":
            if recv_data["buy_flag"] is False:
                return
            message_detail = {"stock_code": recv_data["stock_code"],
                              "stock_name": recv_data["stock_name"],
                              "price": recv_data["buy_price"],
                              "action_type": "买入",
                              "buy_time": recv_data["buy_time"],
                              "stop_point": recv_data["stop_point"],
                              "mirror_point": recv_data["mirror_point"],
                              "cost_slippage": recv_data["cost_slippage"],
                              "trade_account": recv_data["trade_account"],
                              "trade_qty": recv_data["trade_qty"],
                              "is_autotrade": recv_data["is_autotrade"]
                              }
        elif recv_data["operation"] == "sell":
            message_detail = {"stock_code": recv_data["stock_code"],
                              "stock_name": recv_data["stock_name"],
                              "buy_price": recv_data["buy_price"],
                              "cost_slippage": recv_data["cost_slippage"],
                              "buy_cost_price": recv_data["buy_cost_price"],
                              "buy_time": recv_data["buy_time"],
                              "price": recv_data["sell_price"],
                              "action_type": "卖出",
                              "profile_ratio": recv_data["profile_ratio"],
                              "stage": recv_data["stage"],
                              "sell_type": recv_data["sell_type"],
                              "sell_time": recv_data["sell_time"],
                              "trade_account": recv_data["trade_account"],
                              "trade_qty": recv_data["trade_qty"],
                              "is_autotrade": recv_data["is_autotrade"],
                              }
        else:
            return
        send_header = self.push_api.send_message_header()
        send_content = self.push_api.send_template_message_content(message_detail)
        send_body = self.push_api.send_message_body(send_content, msg_type="interactive")
        self.push_api.request_send_message(send_header, send_body)

    def init_rabbitmq(self):
        # def callback_rabbitmq(ch, method, properties, body):
        #     print('[x] Received %r' % body)
        self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=self.queue_name)
        self.channel.queue_purge(queue=self.queue_name)

    def run_tracing(self):
        self.db_client.init_client()
        it = self.channel.consume(queue=self.queue_name, auto_ack=True)
        for _, _, body in it:
            recv_data = json.loads(body)
            if recv_data["operation"] == "buy":
                if recv_data["trade_account"] == "00000000":
                    self.db_client.select_db_collection("backtest", "buytracing")
                else:
                    self.db_client.select_db_collection("trade", "buytracing")
                self.db_client.insert_data([recv_data])
                trade_detail = dict()
                trade_detail["code"] = recv_data["stock_code"]
                trade_detail["name"] = recv_data["stock_name"]
                trade_detail["buy_price"] = recv_data["buy_price"]
                trade_detail["buy_time"] = recv_data["buy_time"]
                trade_detail["buy_cost_price"] = recv_data["buy_price"] + recv_data["cost_slippage"]
                trade_detail["trade_account"] = recv_data["trade_account"]
                trade_detail["trade_qty"] = recv_data["trade_qty"]
                trade_detail["sell_type"] = ""
                trade_detail["sell_price"] = -1
                trade_detail["sell_time"] = ""
                trade_detail["profile_ratio"] = 0
                if recv_data["trade_account"] == "00000000":
                    self.db_client.select_db_collection("backtest", "tradetracing")
                else:
                    self.db_client.select_db_collection("trade", "tradetracing")
                self.db_client.insert_data([trade_detail])
            elif recv_data["operation"] == "sell":
                if recv_data["trade_account"] == "00000000":
                    self.db_client.select_db_collection("backtest", "selltracing")
                else:
                    self.db_client.select_db_collection("trade", "selltracing")
                self.db_client.insert_data([recv_data])
                trade_detail = dict()
                trade_detail["code"] = recv_data["stock_code"]
                trade_detail["name"] = recv_data["stock_name"]
                trade_detail["buy_price"] = recv_data["buy_price"]
                trade_detail["buy_time"] = recv_data["buy_time"]
                trade_detail["buy_cost_price"] = recv_data["buy_price"] + recv_data["cost_slippage"]
                trade_detail["trade_account"] = recv_data["trade_account"]
                trade_detail["trade_qty"] = recv_data["trade_qty"]
                trade_detail["sell_type"] = recv_data["sell_type"]
                trade_detail["sell_price"] = recv_data["sell_price"]
                trade_detail["sell_time"] = recv_data["sell_time"]
                trade_detail["profile_ratio"] = recv_data["profile_ratio"]
                if recv_data["trade_account"] == "00000000":
                    self.db_client.select_db_collection("backtest", "tradetracing")
                else:
                    self.db_client.select_db_collection("trade", "tradetracing")
                db_collection = self.db_client.get_selected_collection()
                if recv_data["sell_type"] == "止盈剩余仓位":
                    self.db_client.insert_data([trade_detail])
                else:
                    db_collection.update_one({"code": recv_data["stock_code"], "buy_time": recv_data["buy_time"]}, {'$set': trade_detail})
            # print(recv_data)
        self.db_client.close_client()


if __name__ == "__main__":
    result_tracing = ResultTracing()
    result_tracing.init_rabbitmq()
    result_tracing.run_tracing()